<template>
    <van-button
    :icon="attitude === 1 ? 'good-job':'good-job-o'"
    :class="{liked: attitude === 1}"
    :loading="isLoading"
    @click="onLike"/>
</template>

<script>
import { addLike, deleteLike } from '@/api/article'

export default {
    name: 'LikeArticle',
    props: ['attitude', 'articleId'],
    model: {
        prop: 'attitude',
        event: 'updateLiked'
    },
    data () {
        return {
            isLoading: false
        }
    },
    methods: {
        async onLike () {
            this.isLoading = true
            try {
                let status = -1
                if (this.attitude === 1) {
                    // 已点赞->取消点赞
                    await deleteLike(this.articleId)
                } else {
                    // 未点赞->点赞
                    await addLike(this.articleId)
                    status = 1
                }
                this.$emit('updateLiked', status)
                this.$toast.success(status === 1 ? '点赞成功' : '取消点赞')
            } catch (err) {
                this.$toast.fail('操作失败，请稍后重试')
            }
            this.isLoading = false
        }
    }
}
</script>

<style scoped lang="less">
.liked {
    .van-icon {
        color: #e5645f;
    }
}
</style>
